package serie05;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import serie04.Civ;
import serie04.Contact;
import serie04.StdContact;
import serie04.StdPhoneBook;

public class StdPersistentPhoneBook extends StdPhoneBook 
										implements PersistentPhoneBook {
	
	// ATTRIBUTS
	
	private File file;
	
	// CONSTRUCTEURS
	
	public StdPersistentPhoneBook(File file) {
		super();
		if (file == null) {
			throw new IllegalArgumentException("Mauvais fichier");
		}
		this.file = file;
	}
	
	public StdPersistentPhoneBook() {
		super();
		this.file = null;
	}
	
	// REQUETES
	
    public File getFile() {
    	return file;
    }
    
    // COMMANDES
    
    public void setFile(File file) {
    	if (file == null) {
    		throw new IllegalArgumentException("Fichier inexistant");
    	}
    	this.file = file;
    }
    
    public void load() throws IOException, BadSyntaxException {
    	if (getFile() == null) {
    		clear();
			throw new IllegalStateException("Mauvais fichier");
		}
    	if (!getFile().exists() || !getFile().canRead()) {
    		clear();
    		throw new FileNotFoundException("Erreur de lecture du fichier");
    	}
    	clear();
    	BufferedReader input =  new BufferedReader(new FileReader(getFile()));
    	String[] words;
    	String[] numbers;
    	String line = input.readLine();
    	while (line != null) {
    		LINE_RECOGNIZER.reset(line);
    		if (!LINE_RECOGNIZER.matches()) {
    			clear();
    			throw new BadSyntaxException("Mauvaise ligne");
    		}
    		words = line.split(":");
    		Civ c = Civ.values()[Integer.decode(words[0].trim())];
    		numbers = words[3].split(",");
    		List<String> lst = new ArrayList<String>();
    		Contact p = new StdContact(c, words[1].trim(), words[2].trim());
    		for (int i = 0; i < numbers.length; i++) {
    			lst.add(numbers[i].trim());
    		}
    		addEntry(p, lst);
    		line = input.readLine();
    	}
    	input.close();
    }
    
    public void save() throws IOException {
    	if (getFile() == null) {
			throw new IllegalStateException("Mauvais fichier");
		}
    	if (!getFile().exists() || !getFile().canWrite()) {
    		throw new FileNotFoundException(
    			"Erreur d'ecriture dans le fichier"
    		);
    	}
    	BufferedWriter output =  new BufferedWriter(new FileWriter(getFile()));
    	String buffer, num;
    	for (Contact p : contacts()) {
    		buffer = "";
    		num = "";
    		for (String s : phoneNumbers(p)) {
    			if (s.equals(firstPhoneNumber(p))) {
    				num = s;
    			} else {
    				num += "," + s;
    			}
    		}
    		buffer = p.getCivility().ordinal() + ":" + p.getLastName() + ":"
						+ p.getFirstName() + ":" + num
						+ System.getProperty("line.separator");
    		output.write(buffer);
    	}
    	output.close();
    }
    
}
